package com.pinfly.common.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;

/*
 * SafeBufferedReader
 *
 * This implements a safe version of BufferedReader so that it does not hang
 * the thread when reading streams where lines end in carriage returns.
 * See Java Network Programming - 2nd Edition, O'Reilly pg. 107-108.
 */

public class SafeBufferedReader extends BufferedReader
{
    public SafeBufferedReader (Reader in)
    {
        super (in, 1024);
    }

    public SafeBufferedReader (Reader in, int bufferSize)
    {
        super (in, bufferSize);
    }

    private boolean lookingForLineFeed = false;

    public String readLine () throws IOException
    {
        StringBuffer sb = new StringBuffer ("");
        while (true)
        {
            int c = read ();
            if (c == -1) // end of stream
            {
                return (null);
            }
            else if (c == '\n')
            {
                if (lookingForLineFeed)
                {
                    lookingForLineFeed = false;
                    continue;
                }
                else
                {
                    return (sb.toString ());
                }
            }
            else if (c == '\r')
            {
                lookingForLineFeed = true;
                return (sb.toString ());
            }
            else
            {
                lookingForLineFeed = false;
                sb.append ((char) c);
            }
        }
    }

}
